package com.yvan.leto.server.service;

import com.google.common.collect.Lists;
import com.yvan.leto.SegmentHelper;
import com.yvan.leto.server.dao.RepositoryPersistent;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.Properties;

@Component(ConfigParserService.PARSER_PREFIX + SegmentHelper.PROP)
public class PropertiesParser implements IParser {

    @Autowired
    private RepositoryPersistent repositoryPersistent;

    @Override
    @SneakyThrows
    public String process(ParserContext context) {
        List<File> resourceList = Lists.newArrayList();
        for (val relativePath : context.getSegment().getConfigFiles()) {
            resourceList.addAll(repositoryPersistent.repositoryEnvFileList(context.getEnv(), relativePath));
        }

        val properties = new Properties();
        for (val r : resourceList) {
            @Cleanup val is = new FileInputStream(r);
            properties.load(is);
        }

        @Cleanup ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        properties.store(outputStream, context.getProject().getName() + "." + context.getSegment().getName());
        return new String(outputStream.toByteArray(), "utf-8");
    }
}
